package com.eascs.web.o2o.web.reward.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.web.o2o.web.reward.dao.BaseDao;
import com.eascs.web.o2o.web.reward.entity.LoanDetailForm;
import com.eascs.web.o2o.web.reward.entity.ValidLoan;
import com.eascs.web.o2o.web.reward.service.ValidLoanService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@Service
public class ValidLoanServiceImpl implements ValidLoanService{

	private static Logger log = LoggerFactory.getLogger(OverdualReportServiceImpl.class);

	@Autowired
	BaseDao baseDao;
	
	@Override
	public PageResult<Object[]> reportForValidLoan(LoanDetailForm entity, String type) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, entity.getPageSize(),
				entity.getShowPage());
		StringBuffer querySql = new StringBuffer();
		if (type.equals("search")) {
			querySql.append("select t_month,province_name,user_code,user_name,"
					+ "evaluate_type,cur_new_loan_amount,cur_continue_loan_amount,"
					+ "cur_overdue_amount,cur_receive_loan_amount,cur_new_coefficient,"
					+ "continue_loan_coefficient,valid_loan_amount "
					+ "from dm_reward_valid_loan_total_amount "
					+ "where /**DATA_PERMISSION(ltd)**/ 1=1 ");
		} else if (type.equals("download")) {
			querySql.append(
					"select t_month,province_code,province_name,user_no,user_code,user_name,"
					+ "evaluate_type,cur_new_loan_amount,cur_continue_loan_amount,"
					+ "cur_overdue_amount,cur_receive_loan_amount,cur_new_coefficient,"
					+ "continue_loan_coefficient,valid_loan_amount,ltd,ltd_code,ltd_name "
					+ "from dm_reward_valid_loan_total_amount where 1=1 ");
		}
		sqlPageQuery.setQuerySql(querySql.toString());
		if (!StringUtil.isEmpty(entity.getCheckMonth())) {
			sqlPageQuery.setQuerySql(sqlPageQuery.getQuerySql() + " and t_month= ? ");
			sqlPageQuery.addParam(entity.getCheckMonth());
		}		
		if (!StringUtil.isEmpty(entity.getProvinceName())) {
			sqlPageQuery.setQuerySql(sqlPageQuery.getQuerySql() + " and province_name=?");
			sqlPageQuery.addParam(entity.getProvinceName());
		}		
		return baseDao.findDataWithPage(sqlPageQuery);
	}

	@Override
	@Transactional("transactionManagerDbForReward")
	public void addValidLoanList(List<List<Object>> result) {
		baseDao.executeSql("delete from dm_reward_valid_loan_total_amount where t_month = DATE_FORMAT(DATE_SUB(now(),INTERVAL 1 month),'%Y-%m')");
		User user=UserHolder.getUser();
		//将excel中的数据更新到数据库中
		if(result!=null&&result.size()>0){
			for (int i = 0; i < result.size(); i++) {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				List<Object> list = (List) result.get(i);
				ValidLoan validLoan = new ValidLoan();
				validLoan.setT_month(list.get(0).toString());
				validLoan.setProvince_code(list.get(1).toString());
				validLoan.setProvince_name(list.get(2).toString());
				validLoan.setUser_no(list.get(3).toString());
				validLoan.setUser_code(list.get(4).toString());
				validLoan.setUser_name(list.get(5).toString());
				validLoan.setEvaluate_type(list.get(6).toString());
				validLoan.setCur_new_loan_amount((BigDecimal)list.get(7));
				validLoan.setCur_continue_loan_amount((BigDecimal)list.get(8));
				validLoan.setCur_overdue_amount((BigDecimal)list.get(9));
				validLoan.setCur_receive_loan_amount((BigDecimal)list.get(10));
				validLoan.setCur_new_coefficient((BigDecimal)list.get(11));
				validLoan.setContinue_loan_coefficient((BigDecimal)list.get(12));
				validLoan.setCvalid_loan_amount((BigDecimal)list.get(13));
				validLoan.setLtd(list.get(14) == null?null:list.get(14).toString());
				validLoan.setLtd_code(list.get(15) == null?null:list.get(15).toString());
				validLoan.setLtd_name(list.get(16) == null?null:list.get(16).toString());
				validLoan.setIs_lock("N");
				validLoan.setCreate_user(user.getCname());
				validLoan.setCreate_date(new Date());
				validLoan.setUpdate_user(user.getCname());
				validLoan.setUpdate_date(new Date());
				validLoan.setConfirm_user(user.getCname());
				validLoan.setConfirm_date(new Date());
				baseDao.saveEntity(validLoan);
			}
		}else{
			log.error("导入的数据为空，事务回滚");
			throw new RuntimeException("导入的数据为空，请重新导入！");
		}
	}

	@Override
	public String getId(String checkMonth, String userName) {
		List<Object[]> list = baseDao.executeSqlForObjectArray("select id from dm_reward_valid_loan_total_amount "
				+ "where t_month='"+checkMonth+"' and user_name='"+userName+"'");
		return list.get(0)[0].toString();
	}

}
